<template>
  <div class='container'>
    <el-card>
      <h3 style="font-weight:normal;font-size:16px;margin-top:0">试题录入</h3>
      <el-divider></el-divider>
      <!-- 表单 -->
      <el-form ref="form" label-width="180px" class="formInfo" :model="formData" :rules="rules">
        <el-form-item prop="subjectID" label="学科：">
            <el-select v-model="formData.subjectID" placeholder="请选择" style="width:410px" @change="subjectChange">
              <el-option v-for="item in subjectList" :key="item.id" :label="item.subjectName" :value="item.id"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item prop="catalogID" label="目录：">
            <el-select v-model="formData.catalogID" placeholder="请选择" style="width:410px">
              <el-option v-for="item in directoryList" :key="item.id" :label="item.directoryName" :value="item.id"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item prop="enterpriseID" label="企业：">
            <el-select v-model="formData.enterpriseID" placeholder="请选择" style="width:410px">
              <el-option v-for="item in companyList" :key="item.id" :label="item.company" :value="item.id"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item prop="province" label="城市：" style="display:inline-block">
          <el-select v-model="formData.province" placeholder="请选择" style="margin-right:2px" @change="provinceChange">
            <el-option v-for="item in provinces" :key="item" :label="item" :value="item" />
           </el-select>
          <!-- <el-select v-model="formData.city" placeholder="请选择" style="margin-left:2px">
            <el-option v-for="item in cities" :key="item" :label="item" :value="item" />
          </el-select> -->
        </el-form-item>

        <el-form-item prop="city" style="display:inline-block" label-width="0">
          <el-select v-model="formData.city" placeholder="请选择" style="margin-left:2px">
            <el-option v-for="item in cities" :key="item" :label="item" :value="item" />
          </el-select>
         </el-form-item>

        <el-form-item prop="direction" label="方向：">
            <el-select v-model="formData.direction" placeholder="请选择" style="width:410px">
              <el-option v-for="item in directories" :key="item" :label="item" :value="item"></el-option>
            </el-select>
         </el-form-item>

        <el-form-item prop="questionType" label="题型：">
          <el-radio-group v-model="formData.questionType">
            <el-radio
            v-for="(item, index) in quesTypes"
            :key="item"
            :label="`${index + 1}`"
            >{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="difficulty" label="难度：">
          <el-radio-group v-model="formData.difficulty">
            <el-radio
            v-for="(item, index) in difficulties"
            :key="item"
            :label="`${index + 1}`"
            >{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 题干： -->
        <el-form-item prop="question" label="题干：">
          <vue-editor v-model="formData.question" :editor-toolbar="customToolbar" />
        </el-form-item>

        <el-form-item v-if="formData.questionType === '1'" label="选项：">
          <el-radio-group v-model="radioValue">
            <el-radio
            v-for="item in formData.options"
            :key="item.code"
            :label="item.code"
            style="display:block;padding-top:10px;margin-left:10px"
            >
            <span>{{ item.code }}：</span>
            <el-input v-model="item.title" style="margin-right:5px"/>
            <UploadImage :fileList="[{url: item.img}]" class="uploadImge"></UploadImage>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-else-if="formData.questionType === '2'" label="选项：">
          <el-checkbox-group v-model="checkList">
            <el-checkbox
            v-for="item in formData.options"
            :key="item.code"
            :label="item.code"
            style="display:block;padding-top:10px;margin-left:10px"
            >
            <span>{{ item.code }}：</span>
            <el-input v-model="item.title" style="margin-right:5px"/>
            <UploadImage :fileList="[{url: item.img}]" class="uploadImge"></UploadImage>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 增加答案 -->
        <el-form-item label="">
          <el-button :disabled="+formData.questionType !== 2" type="danger" size="small" @click="addAnswer">+增加选项与答案</el-button>
        </el-form-item>
        <!-- 视频解析 -->
        <el-form-item label="解析视频">
           <el-input v-model="formData.videoURL" style="width:410px" />
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item prop="answer" label="答案解析：">
          <vue-editor v-model="formData.answer" :editor-toolbar="customToolbar" />
        </el-form-item>

        <el-form-item label="题目备注：">
        <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="formData.remarks" autocomplete="off" style="min-height:33px;width:410px"></el-input>
        </el-form-item>

        <el-form-item label="试题标签：">
          <el-select v-model="formData.tags" placeholder="请选择试题标签" style="width:410px">
            <el-option v-for="item in tags" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="">
          <el-button type="primary" @click="commit">确认提交</el-button>
        </el-form-item>

      </el-form>

    </el-card>
  </div>
</template>

<script>
import { VueEditor } from 'vue2-editor'
import { provinces, citys } from '@/api/hmmm/citys'
import { list } from '@/api/hmmm/subjects.js'
import { simple } from '@/api/hmmm/tags.js'
import { list as directoryList } from '@/api/hmmm/directorys.js'
import { list as companysList } from '@/api/hmmm/companys.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
import UploadImage from '@/module-hmmm/components/UploadImage'
export default {

  components: {
    VueEditor,
    UploadImage
  },

  data () {
    return {
      formData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '', // 题型
        difficulty: '', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: '', isRight: 0 },
          { code: 'B', title: '', img: '', isRight: 0 },
          { code: 'C', title: '', img: '', isRight: 0 },
          { code: 'D', title: '', img: '', isRight: 0 }
        ], // 选项(对象数组)code, title, img, isRight
        videoURL: '', // 解析视频地址
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },

      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: '学科不能为空', trigger: ['blur', 'change'] }
        ],
        catalogID: [
          { required: true, message: '目录不能为空', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
          { required: true, message: '企业名称不能为空', trigger: ['blur', 'change'] }
        ],
        province: [
          { required: true, message: '城市不能为空', trigger: ['blur', 'change'] }
        ],
        direction: [
          { required: true, message: '业务不能为空', trigger: ['blur', 'change'] }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: ['blur', 'change'] }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: ['blur', 'change'] }
        ],
        question: [
          { required: true, message: '题干不能为空', trigger: ['blur', 'change'] }
        ],
        answer: [
          { required: true, message: '答案解析不能为空', trigger: ['blur', 'change'] }
        ]
      },
      // 试题类型
      quesTypes: ['单选', '多选', '简答'],
      // 试题难度
      difficulties: ['简单', '一般', '困难'],
      // 方向
      directories: ['o2o', '外包服务', '企业服务', '互联网金融', '企业咨询', '互联网', '电子商务', '其他'],

      customToolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
        ['blockquote', 'code-block'], // 引用，代码块
        ['image', 'link']
      ],

      checkList: [],
      radioValue: 0,

      provinces: [],
      cities: [],

      // 科目列表
      subjectList: [],
      // 目录列表
      directoryList: [],
      // 所有公司列表
      companyList: [],
      // 标签列表
      tags: []

    }
  },

  created () {
    this.getSubjectList()
    this.getDirectoryList()
    this.getCompanys()
    this.getProvince()
    if (this.$route.query.id) {
      this.getDetailQeus()
    }
  },

  methods: {
    // 获取所有身份
    getProvince () {
      this.provinces = provinces()
    },
    provinceChange (province) {
      this.cities = citys(province)
    },

    addAnswer () {
      const option = String.fromCharCode('A'.charCodeAt(0) + this.formData.options.length)
      this.formData.options.push({ code: option, title: '', img: '', isRight: 0 })
    },
    // 提交
    commit () {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return
        // 处理选项
        if (+this.formData.questionType === 1) { // 单选
          this.formData.options.forEach(item => {
            if (item.code === this.radioValue) {
              item.isRight = 1
            }
          })
        } else if (+this.formData.questionType === 2) { // 多选
          this.checkList.forEach(code => {
            const item = this.formData.options.find(item => item.code === code)
            if (item) item.isRight = 1
          })
        } else {
          this.formData.options = []
        }

        if (this.formData.id) { // 编辑
          await update(this.formData)
          this.$message.success('更新成功')
        } else { // 添加
          await add(this.formData)
          this.$message.success('添加成功')
        }

        // 清空表单
        this.clearForm()
      })
    },

    clearForm () {
      // 清空对话框数据（包括校验的数据）
      this.$refs.form.resetFields()

      this.radioValue = 0
      this.checkList = []
      this.formData.videoURL = ''
      this.formData.tags = []
      this.formData.remarks = ''
    },

    async getSubjectList () {
      const { data: { items } } = await list({
        page: 1,
        pagesize: 50
      })
      console.log(items)
      this.subjectList = items
    },

    async getDirectoryList () {
      const { data: { items } } = await directoryList({
        page: 1,
        pagesize: 50
      })
      this.directoryList = items
    },

    async getCompanys () {
      const { data: { items } } = await companysList({
        page: 1,
        pagesize: 999
      })
      this.companyList = items
    },

    async subjectChange (id) { // 学科改变获取tags
      const { data: tags } = await simple({ subjectID: id })
      this.tags = tags.length ? tags : []
      console.log(tags, 'tags')
    },

    async getDetailQeus () {
      const { data } = await detail({ id: this.$route.query.id })

      const options = data.options

      if (data.questionType === '1') {
        this.radioValue = options.find(item => item.isRight === 1).code
      } else if (data.questionType === '2') {
        options.forEach(item => {
          if (item.isRight === 1) {
            this.checkList.push(item.code)
          }
        })
      }
      this.formData = data
    }
  }

}
</script>

<style scoped lang='scss'>
.uploadImge {
  display: inline-block;
  vertical-align: middle;
  text-align: center;
  // width: 80px;
  // height: 50px;
  line-height: 1
}
</style>
